<template>
  <!-- 角色查询 -->
  <el-row>
    <el-col :span="24">
      <el-card class="box-card" id="card">
        <div slot="header" class="clearfix">
          <span>角色管理</span>
          <span>-您可以通过对角色的信息进行编辑、删除等管理操作。^_^</span>
        </div>
        <!-- 表单显示 -->
        <el-row
          type="flex"
          align="bottom"
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-background="rgb(255,255,255)"
        >
          <el-col :span="12">
            <div id="statistics" style="width: 600px;height:400px;"></div>

            <el-button icon="el-icon-circle-plus-outline" @click="addRole"
              >添加岗位</el-button
            >
          </el-col>
          <el-col :span="12" style="margin-bottom: 50px;">
            <el-table
              :data="tableData"
              style="width: 100%"
              border
              height="330px"
              :default-sort="{ prop: 'id', order: 'ascending' }"
            >
              <el-table-column prop="id" label="编号" width="150" sortable>
                <template slot-scope="scope">
                  <!-- <i class="el-icon-s-flag"></i> -->
                  <span style="margin-left: 10px">{{ scope.row.roleId }}</span>
                </template>
              </el-table-column>
              <el-table-column label="角色名称" width="250">
                <template slot-scope="scope">
                  <span>{{ scope.row.roleName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)"
                    >编辑</el-button
                  >
                  <template v-if="scope.row.roleName == '未分配角色'">
                  </template>
                  <template v-else-if="scope.row.roleName == '管理员'">
                  </template>
                  <template v-else>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" class="pagination">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="form.currentPage"
              :page-sizes="[5, 10, 20, 40]"
              :page-size="form.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              background
            >
            </el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </el-col>

    <!-- 修改角色的卡片 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="modifyData"
        status-icon
        ref="modifyData"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            type="text"
            v-model="modifyData.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="角色说明" prop="roleExplain">
          <el-input
            type="text"
            v-model="modifyData.roleExplain"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <div>
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="resetModify">清空</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 删除角色确认框 -->
    <el-dialog
      title="确定要删除该角色吗？该角色和以下角色存在绑定（角色删除，角色处于未分配角色状态）"
      :visible.sync="dialogTableVisible"
      width="55%"
    >
      <el-row type="flex" class="row-bg" justify="center">
        <el-col :span="18" :offset="2">
          <el-table :data="roleData">
            <el-table-column
              property="roleId"
              label="角色编号"
              width="200"
            ></el-table-column>
            <el-table-column
              property="doctorName"
              label="用户名称"
              width="200"
            ></el-table-column>
            <el-table-column
              property="roleName"
              label="角色名称"
              width="200"
            ></el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div>
        <el-button class="delButton" type="primary" @click="sureToDelete"
          >确定</el-button
        >
        <el-button class="delButton" @click="undelete">取消</el-button>
      </div>
    </el-dialog>

    <!-- 恢复角色 -->
    <el-dialog
      title="该角色之前存在，但是被删除了，是否恢复原来的权限？"
      :visible.sync="recoverDialogTableVisible"
      width="55%"
    >
      <el-row type="flex" class="row-bg" justify="center">
        <el-col :span="18" :offset="2">
          <el-table :data="menuText" height="250">
            <el-table-column
              property="menuText"
              label="存在菜单"
              width="400"
            ></el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div>
        <el-button class="delButton" type="primary" @click="recoverRole('yes')"
          >添加角色并恢复权限</el-button
        >
        <el-button class="delButton" @click="recoverRole('no')"
          >添加角色不恢复权限</el-button
        >
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
export default {
  data() {
    /**
     * 服务次数规格进行验证
     */
    var checkServiceCount = (rule, value, callback) => {
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else if (value < 0) {
          callback(new Error("服务患者数必须大于0"));
        } else {
          callback();
        }
      }, 100);
    };
    return {
      /**
       * 查询信息
       */
      form: {
        currentPage: 1,
        pageSize: 5
      },
      /**
       * 表单显示数据，以及规则
       */
      tableData: [],
      roles: [],
      departments: [],
      total: 5,
      loading: false,
      dialogVisible: false,
      //修改/新增/删除表单
      modifyData: {
        roleId: "",
        roleName: "",
        roleExplain: ""
      },
      /**
       * 规则验证
       */
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ]
      },
      title: "",
      //显示删除角色确认对话框
      dialogTableVisible: false,
      //角色和角色信息
      roleData: [],
      //角色拥有的菜单
      menuText: [],
      //恢复角色对话框
      recoverDialogTableVisible: false,
      //角色ID
      roleId: 0
    };
  },
  methods: {
    onSubmit() {
      this.loading = true;
      this.$axios
        .post("/api/biz/role/page", this.form)
        .then(result => {
          if (result.status != 200) {
            this.$message.error("获取角色信息失败！请联系管理员");
            return;
          }
          let data = result.data.data;
          this.tableData = data.role;
          this.total = data.total;
          this.RoleCount();
          this.loading = false;
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    /**
     * 编辑角色信息按钮
     */
    handleEdit(index, row) {
      this.title = "修改角色信息";
      this.modifyData.roleId = row.roleId;
      this.modifyData.roleName = row.roleName;
      this.modifyData.roleExplain = row.roleExplain;
      this.showDialog();
    },

    /**
     * 显示对话框
     */
    showDialog() {
      this.dialogVisible = true;
    },

    /**
     * 清空数据
     */
    resetModify() {
      this.modifyData.roleName = "";
      this.modifyData.roleExplain = "";
    },

    /**
     * 显示角色名称和角色名称
     */
    handleDelete(index, row) {
      this.modifyData.roleId = row.roleId;
      this.$axios
        .get("/api/biz/user/getRole/" + this.modifyData.roleId)
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            this.roleData = data.data;
            this.dialogTableVisible = true;
          } else {
            this.$message.error("获取角色和角色信息失败！");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    /**
     * 确定删除
     */
    sureToDelete() {
      this.deleteRole(this.modifyData.roleId);
    },
    /**
     * 取消删除
     */
    undelete() {
      this.dialogTableVisible = false;
    },

    /**
     * 删除角色
     */
    deleteRole(id) {
      this.$axios
        .get("/api/biz/role/del/" + id)
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            this.$message({
              type: "success",
              message: "删除成功！"
            });
            this.onSubmit();
          } else {
            this.$message({
              type: "error",
              message: "删除失败！"
            });
          }
          this.dialogTableVisible = false;
        })
        .catch(err => {
          this.$message({
            type: "error",
            message: err
          });
        });
    },

    /**
     * 分页方法
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.form.pageSize = val;
      this.onSubmit();
    },
    handleCurrentChange(val) {
      console.log(`当前页:` + val);
      this.form.currentPage = val;
      this.onSubmit();
    },

    /**
     * 添加角色
     */
    addRole() {
      this.modifyData.roleId = 0;
      this.modifyData.roleName = "";
      this.modifyData.roleExplain = "";
      this.title = "新增岗位信息";
      this.showDialog(undefined, undefined);
    },

    /**
     * 提交按钮
     */
    submit() {
      if (this.title == "修改角色信息") {
        this.modifySubmit("modifyData");
      } else {
        this.addSubmit("modifyData");
      }
    },

    /**
     * 提交修改
     */
    modifySubmit(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.$axios
            .post("/api/biz/role/modify", this.modifyData)
            .then(result => {
              let data = result.data;
              if (data.code == 0) {
                //关闭修改窗口
                this.dialogVisible = false;
                //将内容清空
                this.resetModify();
                //获取列表数据
                this.onSubmit();
                this.$message.success("修改角色成功！");
              } else {
                this.$message.error("修改数据提交失败！");
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        } else {
          return false;
        }
      });
    },

    /**
     * 提交新增
     */
    addSubmit(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.title = "新增角色信息";
          this.$axios
            .post("/api/biz/role/add/", this.modifyData)
            .then(result => {
              let data = result.data;
              console.log(data);
              if (data.code == 0) {
                //关闭修改窗口
                this.dialogVisible = false;
                //将内容清空
                this.resetModify();
                //获取列表数据
                this.onSubmit();
                this.$message.success("新增角色成功！");
              } else if (data.code == 1) {
                //角色存在
                this.$message.error("该角色已存在");
              } else if (data.code == 3) {
                //之前存在
                this.menuText = data.data;
                this.roleId = data.data[0].roleId;
                this.recoverDialogTableVisible = true;
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        } else {
          return false;
        }
      });
    },

    /**
     * 添加角色
     */
    recoverRole(isRestore) {
      this.$axios
        .post("/api/biz/role/restore/", {
          isRestore: isRestore,
          roleId: this.roleId,
          roleExplain: this.modifyData.roleExplain
        })
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            this.recoverDialogTableVisible = false;
            this.roleId = 0;
            this.menuText = [];
            //关闭修改窗口
            this.dialogVisible = false;
            this.$message.success("更新角色成功");
            this.onSubmit();
          } else {
            this.$message.error("更新角色失败");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    /**
     * 获取角色数量
     */
    RoleCount() {
      //获取角色数量
      this.$axios
        .get("/api/biz/role/get/count")
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            this.myEcharts(data.data);
          } else {
            this.$message.error("获取角色数量失败！请联系管理员");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    /**
     * 数量统计图
     */
    myEcharts(data) {
      var chartDom = document.getElementById("statistics");
      var myChart = this.$echarts.init(chartDom);
      var option;

      option = {
        tooltip: {
          trigger: "item"
        },
        legend: {
          top: "5%",
          left: "center"
        },
        series: [
          {
            name: "Access From",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2
            },
            label: {
              show: false,
              position: "center"
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "40",
                fontWeight: "bold"
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    }
  },

  //页面初始化时执行
  mounted() {
    this.onSubmit();
  }
};
</script>

<style scoped>
#card {
  width: 100%;
  margin: 0px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
  border-bottom: 1px solid #ebeef5;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.clearfix {
  text-align: left;
}
.clearfix > span:last-child {
  color: #333333;
  font-size: 13px;
}
.clearfix > span:first-child {
  font-weight: bold;
  color: #59a6f5;
  margin-right: 20px;
}
.queryButton {
  padding-bottom: 20px;
}
.pagination {
  padding-top: 20px;
}

.el-form-item__content {
  margin-left: 100px;
  margin-right: 50px;
}
.el-select {
  width: 100%;
}
.el-dialog__body {
  padding-top: 10px;
}
.delButton {
  margin: 10px 50px;
}
</style>
